package com.example.by.mdb.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

import com.example.by.mdb.R;
import com.example.by.mdb.fragment.MyTaskFragment;
import com.example.by.mdb.fragment.QuitFragment;
import com.example.by.mdb.fragment.SpotInspectionFragment;

public class MainActivity extends AppCompatActivity {
    private FragmentTabHost tabHost;
    private LayoutInflater inflater;
    public String workerName = null, groupNo;
    private App app;
    private Class fragments[] = {MyTaskFragment.class, SpotInspectionFragment.class, QuitFragment.class};
    private String[] titles = {"我的任务", "调维点检", "退出登录"};
    private int images[] = {R.mipmap.task, R.mipmap.check, R.mipmap.quit};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        Intent intent = getIntent();
        workerName = intent.getStringExtra("name");
        groupNo = app.getGroupNo();
    }

    private void init() {
        app = (App) getApplication();
        inflater = LayoutInflater.from(this);
        tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        tabHost.setup(this, getSupportFragmentManager(), R.id.maintabcontent);
        for (int i = 0; i < fragments.length; i++) {
            TabSpec tabSpec = tabHost.newTabSpec(titles[i]).setIndicator(getTabItemView(i));
            tabHost.addTab(tabSpec, fragments[i], null);
        }
    }

    long oldTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long time = System.currentTimeMillis();
            if (time - oldTime > 1000) {
                Toast.makeText(getApplicationContext(), "再次点击退出程序", Toast.LENGTH_SHORT).show();
            } else {
                finish();
            }
            oldTime = time;
        }
        return true;
    }

    private View getTabItemView(int index) {
        View view = inflater.inflate(R.layout.tab_item, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(images[index]);

        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(titles[index]);

        return view;
    }
}
